import { loginApi } from "@/apis/user";
import { defineStore } from "pinia";
import { ref } from "vue";
import { useCartStore } from "./cartStore";
import { getNewCartApi, mergeCartApi } from "@/apis/cart";

export const useUserStore = defineStore('user', () => {
    const cartSore = useCartStore()

    const userInfo = ref([])
    const getUserInfo = async ({ account, password }) => {
        const res = await loginApi({ account, password })
        userInfo.value = res.result
        // 合并购物车
        const data = cartSore.cartList.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count
            }
        })
        await mergeCartApi(data) 
        // 合并后获取最新购物车列表       
        cartSore.updateNewCartList()
    }
    // 退出清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {}
        // 清除购物车数据
        cartSore.clearCart()
    }
    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }
},
    {
        persist: true
    }
)